/*
 * @Author: liuYang codkly@gmail.com
 * @Date: 2022-10-26 22:55:19
 * @LastEditors: liuYang codkly@gmail.com
 * @LastEditTime: 2022-11-09 09:33:26
 * @FilePath: \coding\blog\blog_server\src\middleware\checkToken.js
 * @Description: 
 * 暂无备注
 */
// 单独的创建一个中间件，然后在app.js中注册使用
const jwt = require('jsonwebtoken')
let whiteList = ['/user/register','/user/login','/user/info']

async function check(ctx, next) {
    let url = ctx.url.split('?')[0]
    // 如果是登陆页面和注册页面就不需要验证token了 
    console.log('======',url)
    await next()
    return
    if(url == '/'){
        ctx.body = {
            status: 200,
            message: '看卅子'
        }
    }
    if (
        whiteList.indexOf(url)>-1||
        url == '/user/adminLogin' ||
        // 前端
        url == '/article/pageList' ||
        url == '/article/hot' ||
        url == '/article/detail' ||
        (url.indexOf('/file/imgs/') > -1) ||
        url == '/notice/pageList' ||
        url == '/comment/list' ||
        url == '/comment/add' ||
        url == '/comment/reply' ||
        url == '/links/list' ||
        url == '/info/getMd' ||
        url == '/pages/list' ||
        url == '/pages/detail' ||
        url == '/classify/list' ||
        url == '/article/classifyList'||
        url == '/linksType/listAndType'
    ) {
        await next()
    } else {
        // 否则获取到token
        let token = ctx.request.headers["authorization"]
        if (token) {
            console.log(token)
            try {
                // 如果有token的话就开始解析
                const tokenItem = jwt.verify(token.split("Bearer ")[1], 'itliuyang')
              
                // 将token的创建的时间和过期时间结构出来
                const { iat, exp } = tokenItem
                // 拿到当前的时间
                let data = new Date().getTime();
                // 判断一下如果当前时间减去token创建时间小于或者等于token过期时间，说明还没有过期，否则过期
                if (data / 1000 - iat <= exp) {
                    // token没有过期
                    await next()
                } else {
                    ctx.body = {
                        code: 405,
                        msg: 'token 已过期，请重新登陆'
                    }
                }
            } catch (error) {
                if (error.name == 'JsonWebTokenError') {
                    ctx.body = {
                        code: 405,
                        msg: "无效的token"
                    }
                } else if (error.name == 'TokenExpiredError') {
                    ctx.body = {
                        code: 405,
                        msg: 'token 已过期，请重新登陆'
                    }
                } else {
                    ctx.body = {
                        code: 405,
                        msg: '錯誤' + error
                    }
                }
            }
        } else {
            ctx.body = {
                status: 405,
                message: '请先登录'
            }
        }
    }
}
module.exports = check